home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Shareware Grab Bag
/
Shareware Grab Bag.iso
/
007
/
tbbyte.arc
/
FRACTION.PAS
next >
Wrap
Pascal/Delphi Source File
|
1985-08-16
|
3KB
|
108 lines
{
Program to demonstrate use of function FRACTION.
The algorithms used in the conversion from decimal to fraction were
adapted from the "PROGRAMMING INSIGHT" column in the May '85 issue
of BYTE magazine, p. 429.
The original was written in BASIC, by Dan Sandberg.
Converted to Turbo Pascal by Roy Collins, 5/5/85
The constant PRECISION may be varied to customize to your needs -
do not set it higher than 36, or you will probably get "Arithmetic
Overflow" errors.
Type "STR" must be defined for use in function FRACTION - it may be
a different size, but should be long enough to hold the longest fraction
you may generate.
Following is the original BASIC code:
100 INPUT A:C=ABS(A):B=1
110 B=B/C:C=(1/C)-INT(1/C):IF C>.001 THEN 110
120 B=INT(B):PRINT A*B;"/";B:GOTO 100
}
program fraction;
const
precision = 4;
type
str = string[80];
var
ch : char;
test_value, term, incr : real;
function fraction(test_value:real; precision:integer):str;
var
quit : boolean;
b,c : real;
s1,s2 : str;
xprecision,
yprecision : real;
begin
xprecision := int(exp(precision*ln(10))); {10**precision}
yprecision := exp(-precision*ln(10)); {10** -precision}
c := abs(test_value);
b := 1;
repeat
if b < xprecision then begin
b := b/c;
c := frac(1/c);
quit := c <= yprecision
end
else
quit := true;
until quit;
b := int(b);
test_value := int((test_value * b) + (yprecision/2));
{ Re-Format REAL to STRING, with no leading or trailing blanks }
str(test_value:12:0,s1);
while ((s1<>'') and (s1[1]=' ')) do
delete(s1,1,1);
str(b:12:0,s2);
while ((s2<>'') and (s2[1]=' ')) do
delete(s2,1,1);
{ Remove extraneous trailing zeros }
while((s1[length(s1)]='0') and (s2[length(s2)]='0')) do begin
delete(s1,length(s1),1);
delete(s2,length(s2),1);
end;
fraction := s1 + ' / ' + s2;
end; (* func fraction *)
begin
write('Do you want to let the demo run itself? (Y/N) ');
repeat
read(kbd,ch);
ch := upcase(ch);
until ch in ['Y','N'];
writeln(ch);
if ch='N' then begin
writeln('To terminate, enter 0.0');
writeln;
repeat
test_value := 0.0;
write('Enter decimal: ');
readln(test_value);
if test_value <> 0 then
writeln('Fraction is ',fraction(test_value,precision));
until test_value = 0.0;
end
else begin { auto run }
write('Enter Initial Value: ');
readln(test_value);
write('Enter Increment: ');
readln(incr);
write('Enter Terminal Value');
readln(term);
writeln;
repeat
writeln(test_value:1:precision,' = ',fraction(test_value,precision));
test_value := test_value + incr;
until test_value>term;
end;
end.